<?php

namespace Admin\Controller;

use Admin\Model\SysAccountModel;
use Admin\Model\UserAccountModel;
use Think\Exception;

class OrderController extends AdminController {

    public function index() {
        $cpage = (int)$_GET['p'] > 0 ? (int)$_GET['p'] : 1;

        $nickname = I('nickname', '');
        $order_id = I('order_id', '', 'trim');
        $date_range = I('date_range', '');
        $status = I('status');
        $where = [];

        $prefix = C('DB_PREFIX');
        if ($order_id) {
            $where["A.order_id"] = $order_id;
        }
        if ($nickname) {
            $user = M('User')->where(array('nickname' => $nickname))->find();
            $where["A.user_id"] = $user['id'];
        }

        if ($date_range) {
            list($start_date, $end_date) = explode('~', $date_range);
            $where["A.add_time"] = ['between', [strtotime($start_date), strtotime($end_date) + (3600 * 24) - 1]];
        }
        if (is_numeric($status) && in_array($status, [0, 1])) {
            $where["A.status"] = $status;
        }

        $result = M('Order')->alias('A')->where($where)
            ->field("A.*,B.nickname,B.mobile,C.name as payment_name")
            ->join($prefix . 'user as B ON A.user_id = B.id')
            ->join($prefix . 'payment as C ON A.method = C.id')
            ->page($cpage, $this->page_size)
            ->order("id DESC")->select();
        $count = M('Order')->alias('A')->where($where)->count();
        $Page = new \Think\Page($count, $this->page_size);
        $this->assign('result', $result);
        $this->assign('page', $Page->show());
        $this->display();
    }

    /**
     * 补单操作
     */
    public function valid() {
        $order_id = I('order_id');
        $order = M('Order')->where(['order_id' => $order_id])->find();
        if (empty($order)) {
            return $this->error('该订单不存在');
        }
        if ($order['status'] != 0) {
            return $this->error('该订单不能补单');
        }

        M()->startTrans();
        try {
            //改变订单状态
            M('Order')->where(['id' => $order['id']])->save([
                'status' => 1,
                'update_time' => time(),
            ]);
            $amount = $order['amount'];
            //系统奖励
            $recharge_reward = C('setting')['recharge_reward'];
            $recharge_reward = (float)$recharge_reward;
            $reward = 0; //充值返利
            if ($recharge_reward > 0) {
                $recharge_reward = $recharge_reward / 100;
                $reward = sprintf('%.2f', $recharge_reward * $order['amount']);
            }
            if ($reward > 0) {
                $amount += $reward;
            }
            //会员账户加现金
            M('UserWealth')->where(['id' => $order['user_id']])->setInc('balance', $amount);

            $userWealth = M('UserWealth')->where(['id' => $order['user_id']])->find();
            $userData = [];
            $userData[] = [
                'user_id' => $order['user_id'],
                'amount' => $order['amount'],
                'balance' => $userWealth['balance'] - $reward,
                'remark' => "用户在线充值",
                'created_at' => time(),
                'type_id' => UserAccountModel::OP_CASH,
                'source' => UserAccountModel::SC_IN,
            ];

            $sysData = [];
            $sysData[] = [
                'user_id' => $order['user_id'],
                'amount' => $order['amount'],
                'created_at' => time(),
                'remark' => '用户在线充值，手动补单',
                'type_id' => SysAccountModel::OP_CASH,
                'source' => SysAccountModel::OP_IN,
            ];

            if ($reward > 0) {
                $userData[] = [
                    'user_id' => $order['user_id'],
                    'amount' => $reward,
                    'balance' => $userWealth['balance'],
                    'remark' => "用户在线充值奖励",
                    'created_at' => time(),
                    'type_id' => UserAccountModel::OP_CASH,
                    'source' => UserAccountModel::SC_IN,
                ];
                $sysData[] = [
                    'user_id' => $order['user_id'],
                    'amount' => $reward,
                    'created_at' => time(),
                    'remark' => '用户在线充值奖励，手动补单',
                    'type_id' => SysAccountModel::OP_CASH,
                    'source' => SysAccountModel::OP_IN,
                ];
            }
            //写用户日志
            M('UserAccount')->addAll($userData);
            //写系统日志
            M('SysAccount')->addAll($sysData);
        } catch (Exception $e) {
            M()->rollback();
            return $this->error($e->getMessage());
        }

        M()->commit();
        return $this->success('补单成功');
    }

    //删除订单
    public function delete() {
        $id = I('id', 0, 'intval');
        if (empty($id)) {
            $this->error('参数错误');
        }

        $res = M('Order')->where(['id' => $id])->delete();
        if ($res !== false) {
            $this->success('删除成功');
        }

        $this->error('删除失败');
    }

}
